<?php

namespace  Helper;

class Redis
{
    private static $pool;

    public static function getInstance(){
        if(self::$pool){
            $redis  = self::$pool->pop() ;
            defer(function ()use ($redis){
                self::$pool->push($redis);
            });
            return $redis;
        }else{

            $redisConf = Config::getInstance()->get('redis');
//            var_dump('$redisConf',$redisConf);
            $size = $redisConf['POOL_MAX_NUM'];
            self::$pool = new \Swoole\Coroutine\Channel($size);
            for ($i = 0; $i < $size; $i++)
            {
                $redis = new \Swoole\Coroutine\Redis();
                $res = $redis->connect($redisConf['host'], $redisConf['port']);

                if ($res == false)
                {
                    var_dump("failed to connect redis server.");
                    continue ;
                }
                else
                {   $redis->auth($redisConf['auth']);
                    $redis->select(1);


                    self::$pool->push($redis);
                }
            }

//            var_dump('count',self::$pool->length());


            return  self::$pool->pop();
        }
    }

    public static function clear(){

        $poolLength = self::$pool->length();

        for ($i=0;$i< $poolLength;$i++){


        }

    }


}